package com.recipe.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.recipe.common.config.RedisUtil;
import com.recipe.entity.Dish;
import com.recipe.entity.DishLabel;
import com.recipe.entity.User;
import com.recipe.entity.vo.DishVo;
import com.recipe.enums.DishCollectStatusEnum;
import com.recipe.mapper.DishCollectMapper;
import com.recipe.entity.DishCollect;
import com.recipe.service.DishCollectService;
import com.recipe.service.DishLabelService;
import com.recipe.service.DishService;
import com.recipe.service.UserService;
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * (DishCollect)表服务实现类
 *
 * @author lzk
 * @since 2024-06-18 13:53:50
 */
@Service("dishCollectService")
@RequiredArgsConstructor
public class DishCollectServiceImpl extends ServiceImpl<DishCollectMapper, DishCollect> implements DishCollectService {

    private final UserService userService;

    private final RedisUtil redisUtil;

    private final DishService dishService;

    private  final  RocketMQTemplate rocketMQTemplate;

    private final DishLabelService dishLabelService;

    private static final String DISH_COLLECT_COUNT_KEY = "dish.collect.count";

    private static final String DISH_COLLECT_DETAIL_KEY = "dish.collect.detail";

    @Override
    public void add(DishCollect dishCollect) {
        DishCollect dishCollect1=new DishCollect();

        Long userId = dishCollect.getUserid();
        Long dishId = dishCollect.getDishid();
        int status=1;
        if(isCollected(dishId.toString(),userId.toString())){
            status = 0;
        }
        dishCollect1.setUserid(userId);
        dishCollect1.setStatus(status);
        dishCollect1.setDishid(dishId);
        rocketMQTemplate.convertAndSend("dish-collect", JSON.toJSONString(dishCollect1));
        String detailKey = DISH_COLLECT_DETAIL_KEY + "." + dishId + "." + userId;
        String countKey = DISH_COLLECT_COUNT_KEY + "." + dishId;
        if(DishCollectStatusEnum.COLLECT.code==status){
            redisUtil.increment(countKey, 1);
            redisUtil.set(detailKey, "1");
        }else{
            Integer count = redisUtil.getInt(countKey);
            if (Objects.isNull(count) || count <= 0) {
                return;
            }
            redisUtil.increment(countKey, -1);
            redisUtil.del(detailKey);
        }
    }

    @Override
    public Integer getCollectCount(long dishId) {
        String countKey = DISH_COLLECT_COUNT_KEY + "." + dishId;
        Integer count = redisUtil.getInt(countKey);
        if (Objects.isNull(count) || count <= 0) {
            return 0;
        }
        return count;
    }
    @Override
    public void deleteById(DishVo dishVo) {
        long dishId = dishVo.getDishId();
        this.removeById(dishId);
        User currentUser = userService.getUserByUserName(dishVo.getUsername());
        Long userId = currentUser.getId();
        redisUtil.del(DISH_COLLECT_DETAIL_KEY + "." + dishId+"."+userId);
        redisUtil.increment(DISH_COLLECT_COUNT_KEY + "." + dishId, -1);
        try {
            Thread.sleep(1000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        redisUtil.del(DISH_COLLECT_DETAIL_KEY + "." + dishId+"."+userId);
    }
    public Boolean isCollected(String dishId, String userId) {
        String detailKey = DISH_COLLECT_DETAIL_KEY + "." + dishId + "." + userId;
        return redisUtil.exist(detailKey);
    }

    @Override
    public List<Dish> getMyCollect(String username) {
        User user = userService.getUserByUserName(username);
        Long userId = user.getId();
        LambdaQueryWrapper<DishCollect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishCollect::getUserid, userId);
        List<DishCollect> list = this.list(queryWrapper);
        if (list != null && list.size() > 0) {
            List<Long> dishIdList = list.stream().map(DishCollect::getDishid).collect(Collectors.toList());
            LambdaQueryWrapper<Dish> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.in(Dish::getId, dishIdList);
            List<Dish> dishList = dishService.list(queryWrapper1);

            dishList.forEach(dish -> {
                Long labelid = dish.getLabelid();
                DishLabel dishLabel = dishLabelService.getById(labelid);

                dish.setLabelName(dishLabel.getLabelname());

            });

            return dishList;
        }

        return null;
    }

    @Override
    public void synLikedByMessage(DishCollect dishCollect) {
        List<DishCollect> dishCollectList=new LinkedList<>();
        dishCollectList.add(dishCollect);
        this.saveOrUpdateBatch(dishCollectList);
    }
}

